<template>
  <div>
    <div class="margin-container-list">
      <div class="pad-b-20 pad-t-20">
        <el-button type="primary" @click="handleCreate()">添加套餐</el-button>
      </div>
      <div class="top-operate-default">
        <div class="search-item">
          <label>商品搜索：</label>
          <el-select class="select-class" v-model="textCol" style="width: 120px">
            <el-option label="套餐名称" value="title"></el-option>
            <el-option label="套餐货号" value="goodsCode"></el-option>
            <el-option label="套餐条码" value="goodsBarCode"></el-option>
            <el-option label="外部编码" value="externalCode"></el-option>
            <el-option label="子商品名称" value="skuTitle"></el-option>
            <el-option label="子商品货号" value="skuGoodsCode"></el-option>
            <el-option label="子商品条码" value="skuGoodsBarCode"></el-option>
            <el-option label="子商品外部编码" value="skuExternalCode"></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model.trim="searchKeyword" placeholder="请输入关键词" style="width: 320px"></el-input>
          <label class="font-14 pad-l-5">套餐品牌：</label>
          <el-select class="select-class" v-model="brandId" style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in listBrands"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId">
            </el-option>
          </el-select>
          <label class="font-14 mar-l-20">套餐分类：</label>
          <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select placeholder="选择套餐分类" :options="categoryData" class="special-input" clearable></el-cascader>
          <label class="font-14 mar-l-20">直播商品库：</label>
          <el-select v-if="getVersionType() == 1 || getVersionType() == 4" v-model="searchListQuery.liveGoodsType" style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="已加入" value="1"></el-option>
            <el-option label="未加入" value="0"></el-option>
          </el-select>
          <label class="font-14 mar-l-20" v-if="enterpriseConfig.anchorSelectionAuthority == '1'">主播选品库：</label>
          <el-select v-if="(getVersionType() == 1 || getVersionType() == 4) && enterpriseConfig.anchorSelectionAuthority == '1'" v-model="searchListQuery.selectionGoodsType" style="width: 120px">
            <el-option label="全部" value=" "></el-option>
            <el-option label="已加入" value="1"></el-option>
            <el-option label="未加入" value="0"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!--商品状态 -->
      <div class="tabs-box mar-t-20">
        <el-tabs type="card" v-model="searchListQuery.goodsStatus" @tab-click="goodsStatusClick">
          <el-tab-pane label="全部" name="2"></el-tab-pane>
          <el-tab-pane label="上架中" name="1"></el-tab-pane>
          <el-tab-pane label="已下架" name="0"></el-tab-pane>
        </el-tabs>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="entityList" @selection-change="handleSelectionChange" v-loading="listLoading"
          element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header" row-class-name="default-row">
          <el-table-column width="50px" type="selection" fixed="left"></el-table-column>
          <el-table-column width="520px" label="组合套餐" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p mar-r-30" @click="handleEdit(scope.row)">
                <label><img :src="scope.row.mainImage" class="user-avatar cursor-p"></label>
                <div class="font-14 pad-l-10 v-align-h height-65">
                  <div class="goods-title">
                    <div class="line-2">
                      <template v-if="scope.row.categoryName">
                        <el-tag size="mini" v-if="scope.row.skuFlag == 1" type="danger" effect="light">多</el-tag>
                      </template>
                      <template v-if="enterpriseConfig.anchorSelectionAuthority == '1' && scope.row.selectionGoodsType == '1'">
                        <el-tag size="mini" class="anchor-tag" type="danger" effect="light">选</el-tag>
                      </template>
                      {{scope.row.title}}
                    </div>
                  </div>
                  <template v-if="scope.row.categoryName">
                    <span class="font-color-6 font-13">[{{scope.row.categoryName}}]</span>
                  </template>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="套餐品牌" prop="brandName"></el-table-column>
          <el-table-column v-if="getVersionType() != 2 && getVersionType() != 3" width="140px" label="零售价">
            <template slot-scope="scope">
              ￥{{scope.row.sellPrice}}
            </template>
          </el-table-column>
          <el-table-column width="140px" label="可用库存">
            <template slot-scope="scope">
              <template v-if="scope.row.stock <= scope.row.stockWarn">
                <span style="color: #dd1100">{{scope.row.stock}}</span>
              </template>
              <template v-else>
                {{scope.row.stock}}
              </template>
            </template>
          </el-table-column>
          <el-table-column width="140px" label="销量">
            <template slot-scope="scope">
              {{scope.row.salesNum}}{{scope.row.unit}}
            </template>
          </el-table-column>
          <el-table-column width="140px" label="状态">
            <template slot-scope="scope">
              <template v-if="scope.row.stock == 0">
                已售空
              </template>
              <template v-else>
                <template v-if="scope.row.goodsStatusRemark">
                  <el-tooltip class="item" effect="dark" :content="scope.row.goodsStatusRemark" placement="top-start">
                    <span style="color: #2d8cf0">{{ dict.upDwonStatusFlag[scope.row.goodsStatus]}}</span>
                  </el-tooltip>
                </template>
                <template v-else>
                  {{ dict.upDwonStatusFlag[scope.row.goodsStatus]}}
                </template>
              </template>
            </template>
          </el-table-column>
          <el-table-column v-if="getVersionType() == 1" width="140px" label="销售库">
            <template slot-scope="scope">
              {{dict.distributionType[scope.row.distributionType]}}
            </template>
          </el-table-column>
          <el-table-column min-width="160px" label="操作" fixed="right" align="right">
            <template slot-scope="scope">
              <template v-if="scope.row.auditType === 0 && getVersionType() === '2'">
                <el-tag type="warning"> 审 核 中 </el-tag>
              </template>
              <template v-else>
                <template v-if="scope.row.goodsStatus === 0 && scope.row.auditType !== 0">
                  <el-button type="text" size="medium" @click="handleUp(scope.row)">上架</el-button>
                </template>
                <template v-if="scope.row.goodsStatus === 1 && scope.row.auditType !== 0">
                  <el-button type="text" size="medium" @click="handleDown(scope.row)">下架</el-button>
                </template>
                <el-button type="text" size="medium" @click="handleEdit(scope.row)">编辑</el-button>
                <el-popover
                  placement="bottom"
                  width="100"
                  trigger="hover"
                  popper-class="popover-class"
                >
                  <el-button class="mar-l-10" type="text" size="medium" slot="reference">更多</el-button>
                  <div>
                    <el-button type="text" size="medium" @click="liveGoodsJoin(scope.row)"  v-if="scope.row.liveGoodsType === 0 && (getVersionType() == '1' || getVersionType() == '4') && scope.row.goodsStatus === 1">加入直播库</el-button>
                  </div>
                  <div>
                    <el-button type="text" size="medium" @click="liveGoodsDelete(scope.row)"  v-if="scope.row.liveGoodsType === 1 && (getVersionType() == '1' || getVersionType() == '4')">移出直播库</el-button>
                  </div>
                  <!-- 开启主播选品 -->
                  <div v-if="enterpriseConfig.anchorSelectionAuthority == '1'">
                    <!-- 加入选品库 -->
                    <el-button type="text" size="medium" @click="openSelectionGoodsDialog(scope.row, '1')"  v-if="scope.row.selectionGoodsType == '0' && (getVersionType() == '1' || getVersionType() == '4') && scope.row.goodsStatus === 1">加入选品库</el-button>
                    <!-- 移出选品库 -->
                    <el-button type="text" size="medium" @click="openSelectionGoodsDialog(scope.row, '0')"  v-if="scope.row.selectionGoodsType == '1' && (getVersionType() == '1' || getVersionType() == '4') && scope.row.goodsStatus === 1">移出选品库</el-button>
                  </div>
                </el-popover>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange"
           @current-change="handleCurrentChange" :current-page="searchListQuery.currentPage"
           :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <div>
        <!-- 选品库dialog -->
        <el-dialog :visible.sync="selectionGoodsVisible" title="加入/移出选品库" width="20%" :center="true">
          <el-header>
            <div>
              <label>操作：</label>
              <el-radio v-model="selectionGoodsForm.selectionGoodsType" label="1" name="1">加入选品库</el-radio>
              <el-radio v-model="selectionGoodsForm.selectionGoodsType" label="0" name="0">移出选品库</el-radio>
            </div>
            <div v-if="selectionGoodsForm.selectionGoodsType == 1">
              <label>平台：</label>
              <el-checkbox :checked="true" disabled>小程序直播</el-checkbox>
            </div>
            <div>
              <label>（抖音/快手等平台需到商品详情页设置）</label>
            </div>
          </el-header>
            <div slot="footer"  class="dialog-footer">
              <el-button type="primary" @click="doSaveSelectionGoodsType">保存</el-button>
              <el-button  @click="closeSelectionGoodsDialog">取消</el-button>
            </div>
        </el-dialog>
        <!-- 直播库dialog -->
        <el-dialog title="" :visible.sync="liveGoodsVisible" :close-on-press-escape="true" :center="true" width="850px">
          <el-form :model="liveGoods" label-position="right" label-width="120px">
            <el-form-item label="商品封面" >
              <el-upload
                list-type="picture-card"
                action="/api/common/uploadFiles"
                accept="image/jpeg,image/gif,image/png,image/bmp"
                name="files"
                :data="uploadParams"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload">
                <img v-if="liveGoods.goodsImgUrl" :src="liveGoods.goodsImgUrl" width="148px" height="148px" style="margin-left: -1px;margin-top: -1px;">
                <i v-else class="el-icon-plus"></i>
              </el-upload>
              <span>建议尺寸：200像素 * 200像素，图片大小不得超过50K。</span>
            </el-form-item>
            <el-form-item label="商品名称" >
              <el-input v-model="liveGoods.title" class="width-per-70" placeholder="请输商品名称"></el-input><br/>
              <span>商品名称必须为3-14个汉字（一个字等于两个英文字符或特殊字符）</span>
            </el-form-item>
            <el-form-item label="价格形式" >
              <el-radio-group v-model="priceType">
                <el-radio v-if="liveGoods.skuFlag == 0" label="1" class="mar-b-10">
                  <span class="width-100 display-inline">一口价</span>
                  <span>价格</span>
                  <el-input v-model="liveGoods.price" class="width-180" type="number">
                    <template slot="append">元</template>
                  </el-input>
                </el-radio><br/>
                <el-radio v-if="liveGoods.skuFlag == 1" label="2" class="mar-b-10">
                  <span class="width-100 display-inline">价格区间</span>
                  <span>价格</span>
                  <el-input v-model="liveGoods.minPrice" class="width-180">
                    <template slot="append">元</template>
                  </el-input>
                  <span class="width-20 display-inline text-align-c">-</span>
                  <el-input v-model="liveGoods.maxPrice" class="width-180" type="number">
                    <template slot="append">元</template>
                  </el-input>
                </el-radio><br/>
                <el-radio v-if="liveGoods.skuFlag == 0" label="3" class="mar-b-10">
                  <span class="width-100 display-inline">显示折扣价</span>
                  <span>原价</span>
                  <el-input v-model="liveGoods.originalPrice" class="width-180">
                    <template slot="append">元</template>
                  </el-input>
                  <span class="width-20 display-inline text-align-c"></span>
                  <span>现价</span>
                  <el-input v-model="liveGoods.nowPrice" class="width-180" type="number">
                    <template slot="append">元</template>
                  </el-input>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div class="flex v-align-c">
            <span class="width-120"></span>
            <el-button type="primary" class="width-110" @click="addLiveGoods(0)">加入</el-button>
            <el-button type="primary" class="width-110" @click="addLiveGoods(1)">加入并审核</el-button>
            <el-button class="width-110" @click="liveGoodsVisible = false">取消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
  import { listGoodsCategory } from '@/api/goods/goods'
  import { getGoodsComboList, upComboGoods, downComboGoods } from '@/api/goods/goods-combo'
  import { listBrand } from '@/api/user/enterpriseBrand'
  import { getToken } from '@/utils/auth'
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import { getLiveGoods, addLiveGoods, liveGoodsDelete, doApplyProjectGoodsPrice } from '@/api/goods/liveGoods'
  import { batchSelectionGoods } from '@/api/goods/goods'
  export default {
    data() {
      return {
        brandCategoryId: '',
        entityList: [],
        total: null,
        keyworkedName: '',
        searchListQuery: {
          enterpriseId: this.getEnterpriseId(),
          supplierId: '',
          currentPage: 1,
          size: 10,
          distributionType: null,
          supplierType: null,
          liveGoodsType: '',
          selectionGoodsType: '',
          title: '',
          goodsStatus: '2'
        },
        // 直播商品库
        liveGoods: {
          liveGoodsId: '',
          goodsImgUrl: '',
          priceType: '1',
          price: '',
          minPrice: '',
          maxPrice: '',
          originalPrice: '',
          nowPrice: '',
          auditStatus: '0',
          goodsId: '',
          enterpriseId: this.getEnterpriseId()
        },
        // 选品库
        selectionGoodsForm: {
          enterpriseId: this.getEnterpriseId(),
          goodsIds: [],
          selectionGoodsType: '1', // 加入选品库
          anchorPlatformShopType: '1' // 默认加入，不可更改
        },
        enterpriseConfig: {
          wholesaleAuthority: 0
        },
        categoryIds: [],
        categoryData: [],
        textCol: '',
        searchKeyword: '',
        listBrands: [],
        listLoading: false,
        shareFileLoading: false,
        brandId: '',
        isDict: false,
        dict: {
          upDwonStatusFlag: {}
        },
        entityVisible: false,
        // 选品库dialog
        selectionGoodsVisible: false,
        // 直播库dialog
        liveGoodsVisible: false,
        priceType: '1'
      }
    },
    created() {
      this.uploadParams = { accessToken: getToken(), enterpriseId: this.getEnterpriseId(), goodsType: 30 }
      this.token = { accessToken: getToken() }
      this.listBrand()
      this.listGoodsCategory()
      this.initEnterpriseConfig()
      this.initPage()
    },
    methods: {
      // 商品状态
      goodsStatusClick() {
        this.handleSearch()
      },
      // 查询
      handleSearch() {
        this.initPage()
      },
      // 重置
      handleReset() {
        this.searchListQuery = {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId()
        }
        this.brandCategoryId = ''
        this.keyworkedName = ''
        this.initPage()
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      // 企业配置
      initEnterpriseConfig() {
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
        }
        this.fileLoading = true
        return (isJPG || isBMP || isGIF || isPNG)
      },
      handleUploadSuccess(res, file) {
        if (res.code === 101) {
          this.liveGoods.goodsImgUrl = res.data[0]
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
      },
      // 分页数据
      initPage() {
        this.listLoading = true
        this.searchListQuery['brandName'] = this.keyworkedName
        this.searchListQuery['brandCategoryId'] = this.brandCategoryId

        this.searchListQuery['textCol'] = this.textCol
        this.searchListQuery['searchKeyword'] = this.searchKeyword

        this.searchListQuery['oneCategoryId'] = ''
        this.searchListQuery['twoCategoryId'] = ''
        this.searchListQuery['threeCategoryId'] = ''
        const categoryIds = this.categoryIds
        if (categoryIds.length === 1) {
          this.searchListQuery['oneCategoryId'] = categoryIds[0]
        }
        if (categoryIds.length === 2) {
          this.searchListQuery['twoCategoryId'] = categoryIds[1]
        }
        if (categoryIds.length === 3) {
          this.searchListQuery['threeCategoryId'] = categoryIds[2]
        }

        getGoodsComboList(this.searchListQuery).then(response => {
          if (response.isError) return
          this.entityList = response.records
          this.total = response.total
          if (!this.isDict) {
            this.dict = response.dict
            this.isDict = true
          }
          this.listLoading = false
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initPage()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initPage()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      closeEls() {
        this.entity.brandLogo = ''
      },
      // 品牌
      listBrand() {
        listBrand(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.listBrands = response.data
        })
      },
      // 编辑
      handleEdit(row) {
        // this.$router.push({ path: '/goods/combo-edit/index', query: { goodsId: row.comboGoodsId, goodsSource: row.goodsSource, currentPage: this.searchListQuery.currentPage.toString(), fromListPage: '30' }})
        const routeData = this.$router.resolve({
          path: '/goods/combo-edit/index',
          query: { goodsId: row.comboGoodsId, goodsSource: row.goodsSource, currentPage: this.searchListQuery.currentPage.toString(), fromListPage: '30' }
        })
        window.open(routeData.href, '_blank')
      },
      // 上架
      handleUp(row) {
        if (!row.sellPrice) {
          this.$message({
            type: 'warning',
            message: '零售价为空无法上架'
          })
          return
        }
        const comboGoodsId = row.comboGoodsId
        upComboGoods(comboGoodsId, this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.$message({
            message: '上架成功',
            type: 'success'
          })
          this.initPage()
        })
      },
      // 下架
      handleDown(row) {
        const comboGoodsId = row.comboGoodsId
        downComboGoods(comboGoodsId)
          .then(response => {
            if (response.isError) return
            this.$message({
              message: '下架成功',
              type: 'success'
            })
            this.initPage()
          })
      },
      // 打开加入直播库dialog
      liveGoodsJoin(row) {
        this.liveGoods = {}
        getLiveGoods(row.comboGoodsId).then(response => {
          if (response.isError) return
          this.liveGoods = response.data
          this.priceType = response.data.priceType ? response.data.priceType.toString() : '1'
          this.liveGoodsVisible = true
        })
      },
      // 加入直播库
      addLiveGoods(auditStatus) {
        if (this.priceType === '1' && (!this.liveGoods.price || this.liveGoods.price <= 0)) {
          this.$message.error('一口价不能为空且要大于0')
          return
        }
        if (this.priceType === '2' && (!this.liveGoods.maxPrice || this.liveGoods.maxPrice <= 0)) {
          this.$message.error('最低价不能为空且要大于0')
          return
        }
        if (this.priceType === '2' && (!this.liveGoods.minPrice || this.liveGoods.minPrice <= 0)) {
          this.$message.error('最高价不能为空且要大于0')
          return
        }
        if (this.priceType === '3' && (!this.liveGoods.originalPrice || this.liveGoods.originalPrice <= 0)) {
          this.$message.error('原价不能为空且要大于0')
          return
        }
        if (this.priceType === '3' && (!this.liveGoods.nowPrice || this.liveGoods.nowPrice <= 0)) {
          this.$message.error('现价不能为空且要大于0')
          return
        }
        this.liveGoods.priceType = this.priceType
        this.liveGoods.enterpriseId = this.getEnterpriseId()
        this.liveGoods.auditStatus = auditStatus
        doApplyProjectGoodsPrice(this.liveGoods).then(response => {
          if (response.isError) return
          if (response.data === true) {
            this.saveGoods()
          } else {
            this.$confirm('您设置的价格与商品当前价格不一致，可能导致直播间显示价格与商品详情页显示价格不一致，确认保存？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.saveGoods()
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
          }
        })
      },
      saveGoods() {
        addLiveGoods(this.liveGoods).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.liveGoodsVisible = false
          this.initPage()
        })
      },
      // 移出直播库
      liveGoodsDelete(row) {
        if (row.auditStatus === 0 || row.auditStatus === 2 || row.auditStatus === 3) {
          let remark = '确定要将商品移出直播商品库？'
          if (row.auditStatus === 2) {
            remark = '此商品将从所有直播间中同时删除，且不可恢复，确定要移出吗？'
          }
          this.$confirm(remark, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            liveGoodsDelete(row.liveGoodsId).then(response => {
              if (response.isError) return
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initPage()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        }
        if (row.auditStatus === 1) {
          this.$alert('商品库审核中的商品不允许移出。', '', {
            confirmButtonText: '关闭'
          })
        }
      },
      // 打开选品库dialog
      openSelectionGoodsDialog(row, selectionGoodsType) {
        this.selectionGoodsForm.goodsIds = []
        this.selectionGoodsForm.selectionGoodsType = selectionGoodsType
        this.selectionGoodsForm.goodsIds.push(row.comboGoodsId)
        this.selectionGoodsVisible = true
      },
      // 关闭选品库dialog
      closeSelectionGoodsDialog() {
        this.selectionGoodsVisible = false
      },
      // 变更商品选品库选择状态
      doSaveSelectionGoodsType() {
        batchSelectionGoods(this.selectionGoodsForm).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '加入/移出选品库成功' })
          this.initPage()
          this.selectionGoodsVisible = false
        })
      },
      // 新增套餐
      handleCreate() {
        this.$router.push({ path: '/goods/combo-edit/index', query: { fromListPage: '30' }})
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
  }
  .v-align-h{
    justify-content: space-between;
    display: flex;
    flex-direction: column;
  }
</style>
